Node.js HTTP Module

Node.js HTTP

अंतर्निहित HTTP मॉड्यूल

Node.js HTTP , HTTP HTTP .

यह मॉड्यूल Node.js में वेब एप्लिकेशन और एपीआई बनाने के लिए आवश्यक है।

HTTP सर्वर

अनुरोधों को संभालने और प्रतिक्रियाएँ भेजने के लिए HTTP सर्वर बनाएँ

HTTP अनुरोध

अन्य सर्वरों से HTTP अनुरोध करें

HTTP तरीके

विभिन्न HTTP तरीकों को संभालें (प्राप्त करें, पोस्ट करें, डालें, हटाएं, आदि)

एक HTTP मॉड्यूल जोड़ा जा रहा है

HTTP मॉड्यूल का उपयोग करने के लिए, require() विधि का उपयोग करके इसे अपने एप्लिकेशन में जोड़ें:

// Using CommonJS require (Node.js default)
const http = require('http');

// Or using ES modules (Node.js 14+ with "type": "module" in package.json)
// import http from 'http';

एक HTTP सर्वर बनाना

HTTP मॉड्यूल की createServer() विधि एक HTTP सर्वर बनाती है जो निर्दिष्ट पोर्ट पर अनुरोधों को सुनती है और प्रत्येक अनुरोध के लिए कॉलबैक फ़ंक्शन निष्पादित करती है।

एक बुनियादी HTTP सर्वर उदाहरण

// Import the HTTP module
const http = require('http');

// Create a server object
const server = http.createServer((req, res) => {
  // Set the response HTTP header with HTTP status and Content type
  res.writeHead(200, { 'Content-Type': 'text/plain' });

  // Send the response body as 'Hello, World!'
  res.end('Hello, World!\n');
});

// Define the port to listen on
const PORT = 3000;

// Start the server and listen on the specified port
server.listen(PORT, 'localhost', () => {
  console.log(`Server running at http://localhost:${PORT}/`);
});

कोड को समझना

http.createServer()- एक नया HTTP सर्वर इंस्टेंस बनाता है
कॉलबैक फ़ंक्शन- प्रत्येक अनुरोध के लिए दो मापदंडों के साथ निष्पादित: req - अनुरोध वस्तु, res - प्रतिक्रिया वस्तु
res.writeHead()- प्रतिक्रिया स्थिति कोड और हेडर सेट करता है
res.end()- एक प्रतिक्रिया भेजता है और कनेक्शन बंद कर देता है
server.listen()- निर्दिष्ट पोर्ट पर सर्वर प्रारंभ करता है

सर्वर चला रहा हूँ

🚀सर्वर कैसे चलाएं:

  • कोड को सर्वर.जेएस नामक फ़ाइल में सहेजें
  • Node.js : node server.js
  • उत्तर देखने के लिए अपने ब्राउज़र में http://localhost:3000 पर जाएँ

HTTP हेडर के साथ कार्य करना

HTTP हेडर आपको अपनी प्रतिक्रिया के साथ अतिरिक्त जानकारी भेजने की अनुमति देते हैं।

स्टेटस कोड और रिस्पॉन्स हेडर सेट करने के लिए res.writeHead() विधि का उपयोग किया जाता है।

उत्तर शीर्षलेख सेट करना

const http = require('http');

const server = http.createServer((req, res) => {
  // Set status code and multiple headers
  res.writeHead(200, {
    'Content-Type': 'text/html',
    'X-Powered-By': 'Node.js',
    'Cache-Control': 'no-cache, no-store, must-revalidate',
    'Set-Cookie': 'sessionid=abc123; HttpOnly'
  });

  res.end('

Hello, World!

'); }); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });

सामान्य HTTP स्थिति कोड

कोड समाचार व्याख्या
200 OK सफल HTTP अनुरोधों के लिए एक स्थिर प्रतिक्रिया
201 Created अनुरोध पूरा हो गया है और एक नया संसाधन बनाया गया है
301 Moved Permanently संसाधन को एक नए URL पर ले जाया गया है
400 Bad Request ब्रांचिंग त्रुटि के कारण सर्वर अनुरोध पर कार्रवाई नहीं कर सकता
401 Unauthorized प्राधिकरण आवश्यक है
404 Not Found अनुरोधित संसाधन नहीं मिल सका
500 Internal Server Error एक अप्रत्याशित स्थिति का सामना करना पड़ा

अनुरोध शीर्षलेख पास करना

req.headers :

const http = require('http');

const server = http.createServer((req, res) => {
  // Log all request headers
  console.log('Request Headers:', req.headers);

  // Get specific headers (case-insensitive)
  const userAgent = req.headers['user-agent'];
  const acceptLanguage = req.headers['accept-language'];

  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end(`User-Agent: ${userAgent}\nAccept-Language: ${acceptLanguage}`);
});

server.listen(3000);

यूआरएल और क्वेरी स्ट्रिंग के साथ काम करना

Node.js URL , URL .

अनुरोध URL तक पहुँचना

req.url URL , .

const http = require('http');

const server = http.createServer((req, res) => {
  // Get the URL and HTTP method
  const { url, method } = req;

  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end(`You made a ${method} request to ${url}`);
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000/');
});

यूआरएल मॉड्यूल के साथ यूआरएल को पार्स करना

यूआरएल मॉड्यूल यूआरएल रिज़ॉल्यूशन और पार्सिंग के लिए उपयोगिताएँ प्रदान करता है।

const http = require('http');
const url = require('url');

const server = http.createServer((req, res) => {
  // Parse the URL
  const parsedUrl = url.parse(req.url, true);

  // Get different parts of the URL
  const pathname = parsedUrl.pathname; // The path without query string
  const query = parsedUrl.query; // The query string as an object

  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({
    pathname,
    query,
    fullUrl: req.url
  }, null, 2));
});

server.listen(3000);

क्वेरी स्ट्रिंग के साथ कार्य करना

उन्नत क्वेरी स्ट्रिंग हेरफेर के लिए, आप क्वेरीस्ट्रिंग पैकेज का उपयोग कर सकते हैं:

const http = require('http');
const { URL } = require('url');
const querystring = require('querystring');

const server = http.createServer((req, res) => {
  // Using the newer URL API (Node.js 10+)
  const baseURL = 'http://' + req.headers.host + '/';
  const parsedUrl = new URL(req.url, baseURL);

  // Get query parameters
  const params = Object.fromEntries(parsedUrl.searchParams);

  // Example of building a query string
  const queryObj = {
    name: 'John Doe',
    age: 30,
    interests: ['programming', 'music']
  };
  const queryStr = querystring.stringify(queryObj);

  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({
    path: parsedUrl.pathname,
    params,
    exampleQueryString: queryStr
  }, null, 2));
});

server.listen(3000);

विभिन्न HTTP विधियों को संभालना

RESTful API आमतौर पर संसाधनों पर अलग-अलग ऑपरेशन करने के लिए अलग-अलग HTTP तरीकों (GET, POST, PUT, DELETE, आदि) का उपयोग करते हैं।

Node.js HTTP HTTP :

const http = require('http');
const { URL } = require('url');

// In-memory data store (for demonstration)
let todos = [
  { id: 1, task: 'Learn Node.js', completed: false },
  { id: 2, task: 'Build an API', completed: false }
];

const server = http.createServer((req, res) => {
  const { method, url } = req;
  const parsedUrl = new URL(url, `http://${req.headers.host}`);
  const pathname = parsedUrl.pathname;

  // Set CORS headers (for development)
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

  // Handle preflight requests
  if (method === 'OPTIONS') {
    res.writeHead(204);
    res.end();
    return;
  }

  // Route: GET /todos
  if (method === 'GET' && pathname === '/todos') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(todos));
  }
  // Route: POST /todos
  else if (method === 'POST' && pathname === '/todos') {
    let body = '';
    req.on('data', chunk => {
      body += chunk.toString();
    });

    req.on('end', () => {
      try {
        const newTodo = JSON.parse(body);
        newTodo.id = todos.length > 0 ? Math.max(...todos.map(t => t.id)) + 1 : 1;
        todos.push(newTodo);
        res.writeHead(201, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(newTodo));
      } catch (error) {
        res.writeHead(400, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ error: 'Invalid JSON' }));
      }
    });
  }

  // Route: PUT /todos/:id
  else if (method === 'PUT' && pathname.startsWith('/todos/')) {
    const id = parseInt(pathname.split('/')[2]);
    let body = '';

    req.on('data', chunk => {
      body += chunk.toString();
    });

    req.on('end', () => {
      try {
        const updatedTodo = JSON.parse(body);
        const index = todos.findIndex(t => t.id === id);

        if (index === -1) {
          res.writeHead(404, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({ error: 'Todo not found' }));
        } else {
          todos[index] = { ...todos[index], ...updatedTodo };
          res.writeHead(200, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify(todos[index]));
        }
      } catch (error) {
        res.writeHead(400, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ error: 'Invalid JSON' }));
      }
    });
  }

  // Route: DELETE /todos/:id
  else if (method === 'DELETE' && pathname.startsWith('/todos/')) {
    const id = parseInt(pathname.split('/')[2]);
    const index = todos.findIndex(t => t.id === id);

    if (index === -1) {
      res.writeHead(404, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ error: 'Todo not found' }));
    } else {
      todos = todos.filter(t => t.id !== id);
      res.writeHead(204);
      res.end();
    }
  }

  // 404 Not Found
  else {
    res.writeHead(404, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ error: 'Not Found' }));
  }
});

const PORT = 3000;
server.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}/`);
});

🔧HTTP विधियों के लिए सर्वोत्तम अभ्यास:

  • GET:एक संसाधन या संसाधनों का सेट प्राप्त करें (निष्क्रिय होना चाहिए)
  • POST:एक नया संसाधन बनाएं (बेवकूफ नहीं)
  • PUT:किसी मौजूदा संसाधन को अपडेट करें या अन्यथा बनाएं (निष्क्रिय)
  • PATCH:किसी संसाधन को आंशिक रूप से अद्यतन करें
  • DELETE:एक संसाधन हटाएं (निष्क्रिय)
  • HEAD:प्रतिक्रिया निकाय के बिना GET के समान
  • OPTIONS:लक्ष्य संसाधन के लिए संचार विकल्पों का वर्णन करें

स्ट्रीमिंग प्रतिक्रियाएँ

Node.js . HTTP .

एक बड़ी फ़ाइल स्ट्रीम करना

const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
  // Get the file path from the URL
  const filePath = path.join(__dirname, req.url);

  // Check if file exists
  fs.access(filePath, fs.constants.F_OK, (err) => {
    if (err) {
      res.statusCode = 404;
      res.end('File not found');
      return;
    }

    // Get file stats
    fs.stat(filePath, (err, stats) => {
      if (err) {
        res.statusCode = 500;
        res.end('Server error');
        return;
      }

      // Set appropriate headers
      res.setHeader('Content-Length', stats.size);
      res.setHeader('Content-Type', 'application/octet-stream');

      // Create read stream and pipe to response
      const stream = fs.createReadStream(filePath);

      // Handle errors
      stream.on('error', (err) => {
        console.error('Error reading file:', err);
        if (!res.headersSent) {
          res.statusCode = 500;
          res.end('Error reading file');
        }
      });

      // Pipe the file to the response
      stream.pipe(res);
    });
  });
});

const PORT = 3000;
server.listen(PORT, () => {
  console.log(`File server running at http://localhost:${PORT}/`);
});

स्ट्रीमिंग के लाभ

मेमोरी क्षमता:हर चीज़ को मेमोरी में लोड करने के बजाय डेटा को टुकड़ों में प्रोसेस करता है
पहली बाइट का सबसे तेज़ समय:डेटा उपलब्ध होते ही भेजना शुरू हो जाता है
पोस्ट तनाव प्रबंधन:रीड स्ट्रीम को रोककर स्वचालित रूप से धीमी शाखाओं को संभालता है

अभ्यास

Node.js HTTP .

http.startServer()
✗ ग़लत! Node.js में "http.startServer()" एक मान्य विधि नहीं है
http.newServer()
✗ ग़लत! "http.newServer()" Node.js में मान्य विधि नहीं है
http.createServer()
✓ ठीक है! "http.createServer()" Node.js में HTTP सर्वर बनाने के लिए उपयोग की जाने वाली उचित विधि है
http.initServer()
✗ ग़लत! "http.initServer()" Node.js में मान्य विधि नहीं है